package com.hotel.BL;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.EntityName;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import data.Agency;
import data.PosCommissionConsole;
import data.ValidityConsole;

public class AgencyLogic extends AbstractBL {
	
	public AgencyLogic(HttpServletRequest req, HttpServletResponse resp)
	{
		this.req = req;
		this.resp= resp;
	}
	
	public Agency GetAgency(long id)
	{
		Key key = KeyFactory.createKey(EntityName.Agency, id);
		try {
			Entity lang = datastore.get(key);
			Agency a = new Agency();
			a.setEntity(lang);
			return a;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	public List<Agency> GetAlltravel(long hotelId,long id)
	{
		Query q = new Query(EntityName.Travel);
		
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL,hotelId);
		Filter filterStatus = new FilterPredicate("status",FilterOperator.EQUAL,true);
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,true);
		Filter filter = CompositeFilterOperator.and(filterHotel, filterStatus, filterAvaliable);
		q.setFilter(filter);
		
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public List<Agency> GetList(List<Entity> entities)
	{
		List<Agency> list = new ArrayList<Agency>();
		for(Entity e : entities)
		{
			Agency a = new Agency();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}

	public Agency AddAgency(long hotelId,String agency,String organization,long displayId) throws EntityNotFoundException{
		Agency a = new Agency();
		a.setHotelId(hotelId);
		a.setDisplayId(displayId);
		a.setAgency(agency);
		a.setOrganization(organization);
		a.setAvaliable(true);
		a.setStatus(true);
		a.setCorporate(false);
		Key k = datastore.put(a.getEntity());
		a.setId(k.getId());
		a.setKey(k);

		return a;
	}
	
	public Agency AddAgencyAdmin(long hotelId,String title,String country,String state,String phone,String email,long displayID) throws EntityNotFoundException{
		Agency a = new Agency();
		a.setHotelId(hotelId);
		a.setDisplayId(displayID);
		a.setAgency(title);
		//a.setCountry(country);
		//a.setState(state);
		//a.setPhone(phone);
		//a.setEmail(email);
		a.setAvaliable(true);
		a.setStatus(true);
		a.setCorporate(false);
		Key k = datastore.put(a.getEntity());
		a.setId(k.getId());
		a.setKey(k);
		return a;
	}
	
	public Agency AddCorporate(long hotelId,String title,String address_main,String country_main,String city_main,String state_main,String zipcode_main
			,String salutation_person,String firstname_person,String lastname_person,String designation_person,String phone_person,String extn_person,String officefax_person,String email_person,
			String mobile_person,String gender_person,Date dateofbirth_person,String websiteperson,String titlebill,String addressbill,String country2,String state2,String citybill,String zipcodebill
			,String salutationbill_contact,String firstname_contactperson,String lastname_contactperson,String designation_contactperson,String officephone_contactperson
			,String extn_contactperson,String officefax_contactperson,String email_contactperson,String mobile_contactperson,String gender_contactperson,Date dateofbirth_contactperson
			,String website_contactperson,String creditlimit,String paymentterms,String commission,String type,long displayId) throws EntityNotFoundException{
		Agency c = new Agency();
		c.setHotelId(hotelId);
		c.setDisplayId(displayId);
		
		//main office
		c.setMainaddress(address_main);
		c.setMaincountry(country_main);
		c.setMaincity(city_main);
		c.setMainstate(state_main);
		c.setMainzipcode(zipcode_main);
		//contact person
		c.setSalutationperson(salutation_person);
		c.setFirstnameperson(firstname_person);
		c.setLastnameperson(lastname_person);
		c.setDesignationperson(designation_person);
		c.setPhoneofficeperson(phone_person);
		c.setExtendperson(extn_person);
		c.setOfficefaxperson(officefax_person);
		c.setEmailperson(email_person);
		c.setMobileperson(mobile_person);
		c.setGenderperson(gender_person);
		c.setDobperson(dateofbirth_person);
		c.setWebsiteperson(websiteperson);
		//billing
		c.setBilltitle(titlebill);
		c.setBilladdress(addressbill);
		c.setBillcountry(country2);
		c.setBillstate(state2);
		c.setBillcity(citybill);
		c.setBillzipcode(zipcodebill);
		//bill contact
		c.setContactsalutaion(salutationbill_contact);
		c.setContactfirstname(firstname_contactperson);
		c.setContactlastname(lastname_contactperson);
		c.setContactdesignation(designation_contactperson);
		c.setContactofficephone(officephone_contactperson);
		c.setContactextend(extn_contactperson);
		c.setContactofficefax(officefax_contactperson);
		c.setContactemail(email_contactperson);
		c.setContactmobile(mobile_contactperson);
		c.setContactgender(gender_contactperson);
		c.setContactdob(dateofbirth_contactperson);
		c.setContactwebsite(website_contactperson);
		c.setCreditlimit(creditlimit);
		c.setPaymentterms(paymentterms);
		c.setDiscount(commission);
		c.setAvaliable(true);
		c.setStatus(true);
		if(type.equals("corporate")){
			c.setCorporate(true);
			c.setOrganization(title);
		}else{
			c.setCorporate(false);
			c.setAgency(title);
		}
		Key k = datastore.put(c.getEntity());
		c.setId(k.getId());
		c.setKey(k);

		return c;
	}
	
	public ValidityConsole GetValidityConsole(long id) {
		Key key = KeyFactory.createKey(EntityName.ValidityConsole, id);
		try {
			Entity lang = datastore.get(key);
			ValidityConsole v = new ValidityConsole();
			v.setEntity(lang);
			return v;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public PosCommissionConsole GetPOSCommissionConsole(long id) {
		Key key = KeyFactory.createKey(EntityName.POSCommissionConsole, id);
		try {
			Entity lang = datastore.get(key);
			PosCommissionConsole pm = new PosCommissionConsole();
			pm.setEntity(lang);
			return pm;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public ValidityConsole AddValidityConsole(long hotelId,Date StartDate,Date EndDate,long consoleId) throws EntityNotFoundException{
		ValidityConsole v = new ValidityConsole();
		v.setHotelId(hotelId);
		v.setStartdate(StartDate);
		v.setEnddate(EndDate);
		v.setConsoleId(consoleId);
		v.setAvaliable(true);
		v.setStatus(true);
		Key k = datastore.put(v.getEntity());
		v.setId(k.getId());
		v.setKey(k);
		if(consoleId != 0){
			Agency a = new AgencyLogic(req, resp).GetAgency(consoleId);
			if(a.getListValidity()!=null&&!a.getListValidity().equals("")){
				a.setListValidity(a.getListValidity()+","+String.valueOf(v.getId()));
			}else{
				a.setListValidity(String.valueOf(v.getId()));
			}
			Key kg = datastore.put(a.getEntity());
			a.setId(kg.getId());
			a.setKey(kg);
		}
		return v;
	}
	public ValidityConsole EditValidityConsole(Date StartDate,Date EndDate,long validityId) throws EntityNotFoundException{	
		ValidityConsole v = GetValidityConsole(validityId);
		v.setStartdate(StartDate);
		v.setEnddate(EndDate);
		Key	k=datastore.put(v.getEntity());
		Entity e = datastore.get(k);
		v = new ValidityConsole();
		v.setEntity(e);

		return v;
	}
	public ValidityConsole DeleteValidityConsole(long validityId, long consoleId) throws EntityNotFoundException{	
		ValidityConsole vc = GetValidityConsole(validityId);
		vc.setAvaliable(false);
		vc.setStatus(false);
		Key	k=datastore.put(vc.getEntity());
		Entity e = datastore.get(k);
		vc = new ValidityConsole();
		vc.setEntity(e);
			Agency a = new AgencyLogic(req, resp).GetAgency(consoleId);
			if(a.getListValidity()!=null){
				String[] listValidity= a.getListValidity().split(",");
				String validityIdString = "";
				for(int i=0;i<listValidity.length;i++){
					if(Long.parseLong(listValidity[i])!=validityId){
						validityIdString += listValidity[i]+",";
					}
				}
				if(!validityIdString.equals(""))
					validityIdString = validityIdString.substring(0, validityIdString.length()-1);
				a.setListValidity(validityIdString);
			}
			Key kg = datastore.put(a.getEntity());
			a.setId(kg.getId());
			a.setKey(kg);
		return vc;
	}
	
	public PosCommissionConsole AddPOSCommissionConsole(long hotelId,long pospointId,Double discount,long consoleId) throws EntityNotFoundException{
		PosCommissionConsole pm = new PosCommissionConsole();
		pm.setHotelId(hotelId);
		pm.setPospointId(pospointId);
		pm.setDiscount(discount);
		pm.setConsoleId(consoleId);
		pm.setStatus(true);
		pm.setAvaliable(true);
		Key k = datastore.put(pm.getEntity());
		pm.setId(k.getId());
		pm.setKey(k);
		if(consoleId != 0){
			Agency a = new AgencyLogic(req, resp).GetAgency(consoleId);
			if(a.getPoscommission()!=null&&!a.getPoscommission().equals("")){
				a.setPoscommission(a.getPoscommission()+","+String.valueOf(pm.getId()));
			}else{
				a.setPoscommission(String.valueOf(pm.getId()));
			}
			Key kg = datastore.put(a.getEntity());
			a.setKey(kg);
			a.setId(kg.getId());
		}
		return pm;
	}
	
	public PosCommissionConsole EditPosCommissionConsole(Double discount,long poscommissionId) throws EntityNotFoundException{	
		PosCommissionConsole pm = GetPOSCommissionConsole(poscommissionId);
		pm.setDiscount(discount);
		Key	k=datastore.put(pm.getEntity());
		Entity e = datastore.get(k);
		pm = new PosCommissionConsole();
		pm.setEntity(e);
		return pm;
	}
	public PosCommissionConsole DeletePosCommissionConsole(long poscommissionId, long consoleId) throws EntityNotFoundException{	
		PosCommissionConsole pm = GetPOSCommissionConsole(poscommissionId);
		pm.setAvaliable(false);
		pm.setStatus(false);
		Key	k=datastore.put(pm.getEntity());
		Entity e = datastore.get(k);
		pm = new PosCommissionConsole();
		pm.setEntity(e);
			Agency a = new AgencyLogic(req, resp).GetAgency(consoleId);
			if(a.getPoscommission()!=null){
				String[] listPOSCommission = a.getPoscommission().split(",");
				String poscommisId = "";
				for(int i=0;i<listPOSCommission.length;i++){
					if(Long.parseLong(listPOSCommission[i])!=poscommissionId){
						poscommisId += listPOSCommission[i]+",";
					}
				}
				if(!poscommisId.equals(""))
					poscommisId = poscommisId.substring(0, poscommisId.length()-1);
				a.setPoscommission(poscommisId);
			}
			Key kg = datastore.put(a.getEntity());
			a.setId(kg.getId());
			a.setKey(kg);
		return pm;
	}
	
	public Agency EditAgency(long id,String agency,String organization) throws EntityNotFoundException{	
		Agency aa = GetAgency(id);
		aa.setAgency(agency);
		aa.setOrganization(organization);
		
		Key	k=datastore.put(aa.getEntity());
		Entity e = datastore.get(k);
		aa = new Agency();
		aa.setEntity(e);

		return aa;
	}
	
	public Agency EditStatus(long id) throws EntityNotFoundException{	
		Agency a = GetAgency(id);
		if(a.isStatus() == true){
			a.setStatus(false);
		}else if(a.isStatus() == false){
			a.setStatus(true);
		}
		Key k = datastore.put(a.getEntity());
		a.setId(k.getId());
		a.setKey(k);
		return a;
	}
	
	public Agency EditCorporate(long id,String title,String address_main,String country_main,String city_main,String state_main,String zipcode_main
			,String salutation_person,String firstname_person,String lastname_person,String designation_person,String phone_person,String extn_person,String officefax_person,String email_person,
			String mobile_person,String gender_person,Date dateofbirth_person,String websiteperson,String titlebill,String addressbill,String country2,String state2,String citybill,String zipcodebill
			,String salutationbill_contact,String firstname_contactperson,String lastname_contactperson,String designation_contactperson,String officephone_contactperson
			,String extn_contactperson,String officefax_contactperson,String email_contactperson,String mobile_contactperson,String gender_contactperson,Date dateofbirth_contactperson
			,String website_contactperson,String creditlimit,String paymentterms,String commission,String type) throws EntityNotFoundException{	
		Agency c = GetAgency(id);
		if(type.equals("corporate"))
			c.setOrganization(title);
		else
			c.setAgency(title);
		//main office
		c.setMainaddress(address_main);
		c.setMaincountry(country_main);
		c.setMaincity(city_main);
		c.setMainstate(state_main);
		c.setMainzipcode(zipcode_main);
		//contact person
		c.setSalutationperson(salutation_person);
		c.setFirstnameperson(firstname_person);
		c.setLastnameperson(lastname_person);
		c.setDesignationperson(designation_person);
		c.setPhoneofficeperson(phone_person);
		c.setExtendperson(extn_person);
		c.setOfficefaxperson(officefax_person);
		c.setEmailperson(email_person);
		c.setMobileperson(mobile_person);
		c.setGenderperson(gender_person);
		c.setDobperson(dateofbirth_person);
		c.setWebsiteperson(websiteperson);
		//billing
		c.setBilltitle(titlebill);
		c.setBilladdress(addressbill);
		c.setBillcountry(country2);
		c.setBillstate(state2);
		c.setBillcity(citybill);
		c.setBillzipcode(zipcodebill);
		//bill contact
		c.setContactsalutaion(salutationbill_contact);
		c.setContactfirstname(firstname_contactperson);
		c.setContactlastname(lastname_contactperson);
		c.setContactdesignation(designation_contactperson);
		c.setContactofficephone(officephone_contactperson);
		c.setContactextend(extn_contactperson);
		c.setContactofficefax(officefax_contactperson);
		c.setContactemail(email_contactperson);
		c.setContactmobile(mobile_contactperson);
		c.setContactgender(gender_contactperson);
		c.setContactdob(dateofbirth_contactperson);
		c.setContactwebsite(website_contactperson);
		c.setCreditlimit(creditlimit);
		c.setPaymentterms(paymentterms);
		c.setDiscount(commission);
		//aa.setCountry(country);
		//aa.setState(state);
		//aa.setPhone(phone);
		//aa.setEmail(email);
		Key	k=datastore.put(c.getEntity());
		Entity e = datastore.get(k);
		c = new Agency();
		c.setEntity(e);

		return c;
	}
	
	public Agency DeleteAgency(long AgencyId) throws EntityNotFoundException{
		Agency a = GetAgency(AgencyId);
		a.setAvaliable(false);
		a.setStatus(false);
		
		Key k = datastore.put(a.getEntity());
		a.setId(k.getId());
		a.setKey(k);

		return a;
	}
	
	public List<Agency> GetAllCorporate4AdminLimit(long hotelId,long offset,long line,String type)
	{
		Query q = new Query(EntityName.Agency);
		
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL,hotelId);
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,true);
		Filter filterCorporate = null;
		if(type.equals("corporate"))
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,true);
		else
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,false);
		Filter filter = CompositeFilterOperator.and(filterHotel, filterAvaliable,filterCorporate);
		
		q.setFilter(filter).addSort("displayId", SortDirection.ASCENDING);
		
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withLimit((int) line).offset((int)offset)));
	}
	
	public List<Agency> GetAllCorporate4Admin(long hotelId,String type)
	{
		Query q = new Query(EntityName.Agency);
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL,hotelId);
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,true);
		Filter filterCorporate = null;
		if(type.equals("corporate"))
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,true);
		else
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,false);
		Filter filter = CompositeFilterOperator.and(filterHotel, filterAvaliable,filterCorporate);
		q.setFilter(filter);
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public long GetMaxAgentDisplayId(long hotelId) throws IOException
	{
		Query q = new Query(EntityName.Agency);
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL, hotelId);
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,true);
		Filter filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,false);
		Filter filter = CompositeFilterOperator.and(filterHotel, filterAvaliable,filterCorporate);
		q.setFilter(filter).addSort("displayId", SortDirection.DESCENDING);
		List<Agency> list = GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withLimit(1)));
		if(list.size()>0)
			return list.get(0).getDisplayId();
		return 0;
	}
	public long GetMaxCorporateDisplayId(long hotelId,String type)
	{
		Query q = new Query(EntityName.Agency);
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL, hotelId);
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,true);
		Filter filterCorporate = null;
		if(type.equals("corporate")){
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,true);
		}else{
			filterCorporate = new FilterPredicate("corporate",FilterOperator.EQUAL,false);
		}
		
		Filter filter = CompositeFilterOperator.and(filterHotel, filterAvaliable,filterCorporate);
		q.setFilter(filter).addSort("displayId", SortDirection.DESCENDING);
		List<Agency> list = GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withLimit(1)));
		if(list.size()>0)
			return list.get(0).getDisplayId();
		return 0;
	}
}
